/**
 *
 */
public class HashBucket {

    static class Node {
        private int key;
        private int val;
        private Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;

    public int usedSize;

    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBucket() {
        array = new Node[10];
    }

    public void put(int key, int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        // cur == null 进行头插法
        node.next = array[index];
        array[index] = node;

        usedSize++;
        // 计算散列因子;
        if (loadFactor() >= DEFAULT_LOAD_FACTOR) {
            // 扩容
            resize();
        }

    }

    private void resize() {
        Node[] tmpArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                // 不记录链表后面的节点 就会找不到
                Node curNext = cur.next;
                int index = cur.key % tmpArray.length;
                // 采用的是头插法
                cur.next = tmpArray[index];
                tmpArray[index] = cur;
                cur = curNext;
            }
        }

        array = tmpArray;
    }

    private float loadFactor() {
        return usedSize * 1.0f / array.length;
    }

    /**
     * 通过key来返回val
     * @param key
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
